package com.demo.controls;

import java.math.BigInteger;

import com.demo.common.model.Message;
import com.demo.common.model.Place;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;

public class MsgController extends BaseController {
	public void index() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		int pageindex = getParaToInt("pageindex", 1);
		int pageSize = getParaToInt("pagesize", 100);
		Page<Message> paginate = Message.dao.paginate(pageindex, pageSize,
				"select *", " from message where fuserid = ? and isread=0 order by id desc",
				userid);
		renderJson(paginate.getList());
		
	}
	public void read() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		int placeid = getParaToInt("id", 0);
		if (placeid != 0) {
			Message bean = Message.dao.findById(placeid);
			if (bean == null || bean.getFuserid() != userid) {
				renderErr(ERR_ILLPAR,"this msg not belong " + userid);
				return;
			} else {
				bean.setIsread(1);
				bean.update();
				renderOK();
				return;
			}
		}else{
			renderErr(ERR_ILLPAR,"no message" );
		}
	}
	/**
	 * 想用户发送一条消息
	 * @param type 消息类型 {@link BaseController#MSGTYPE_ORDER}
	 * @param fuserid 消息接收者用户ID
	 * @param context 
	 * @param fromid 消息来源者的ID 系统发出则为0
	 * @param toid 消息的具体目标ID 比如留言板ID,订单ID
	 */
	public static void add(int type,int fuserid,String context,int fromid,int toid) {
		try {
			Message bean = new Message();
			bean.setCreatetime(BigInteger.valueOf(System.currentTimeMillis()));
			bean.setFromid(fromid);
			bean.setToid(toid);
			bean.setFuserid(fuserid);
			bean.setIsread(0);
			bean.setSummary(context);
			bean.setType(type);
			if (!bean.save()) {
				Log.getLog(MsgController.class).error("save message fail"+bean.toString());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			Log.getLog(MsgController.class).error(e.getMessage());
		}

	}

	public void delete() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		int placeid = getParaToInt("id", 0);
		if (placeid != 0) {
			Place bean = Place.dao.findById(placeid);
			if (bean == null || bean.getFuserid().intValue() != userid) {
				renderErr("this place not belong " + userid);
				return;
			} else {
				bean.delete();
			}
		}
		renderOK();
	}
}